import { useModel } from 'umi';
import { uuid } from './uuid';
import moment from 'moment';

export const useUpload = (prefixPath = 'images') => {
  const { getOssUploadCert, uploadFileToOss, uploadFileToMinio } = useModel('importData');

  const uploadFiles = (files?: File[]) => {
    if (!files?.length) {
      return Promise.resolve([]);
    }
    const fileInfos = files.map((d) => {
      const nameSplit = d.name.split('.');
      const fileName = `${uuid()}.${nameSplit[nameSplit.length - 1]}`;
      return {
        name: fileName,
        path: `${prefixPath}/${moment().format('YYYY-MM-DD')}/${fileName}`,
      };
    });

    const upload = (certConf: any, file: any, index: number) => {
      const uploadToOss = () => {
        const rawFormData: any = {
          name: fileInfos[index].name,
          key: `${certConf.dir}/${fileInfos[index].path}`,
          policy: certConf.policy,
          OSSAccessKeyId: certConf.accessId,
          success_action_status: '200',
          signature: certConf.signature,
          file,
        };

        const formData = new FormData();

        Object.keys(rawFormData).forEach((key: string) => {
          formData.append(key, rawFormData[key]);
        });
        uploadFileToOss(certConf.host, formData).then((res: any) => {
          console.log(res, 'res');
        });
        return uploadFileToOss(certConf.host, formData);
      };

      const uploadToMinio = async () => {
        const config = {
          method: 'PUT',
          body: file,
        };
        return uploadFileToMinio(`${certConf.host}/${certConf.bucketName}${certConf.visitUrls[index]}`, config);
      };

      if (certConf.ossType === 'MINIO_OSS') {
        return uploadToMinio();
      } else {
        return uploadToOss();
      }
    };

    return getOssUploadCert({ keys: fileInfos.map((d) => d.path) }).then((res: any) => {
      return Promise.all(files.map((file, index) => upload(res, file, index))).then(() => res.visitUrls);
    });
  };

  return {
    uploadFiles,
  };
};
